 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkBomSmallPaymentAlipayTmp;
import com.zdkj.subway.rca.mapper.SwCkBomSmallPaymentAlipayTmpMapper;
import com.zdkj.subway.rca.service.SwCkBomSmallPaymentAlipayTmpService;
import com.zdkj.subway.rca.service.SwCkBomSmallPaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.ZoneId;
import java.util.*;

/**
 * BOM小额支付平台数据审核-支付宝临时表
 *
 * @author stw
 * @date 2020-10-27 20:40:06
 */
@Service
public class SwCkBomSmallPaymentAlipayTmpServiceImpl extends ServiceImpl<SwCkBomSmallPaymentAlipayTmpMapper, SwCkBomSmallPaymentAlipayTmp> implements SwCkBomSmallPaymentAlipayTmpService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkBomSmallPaymentAlipayTmpServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd";
    @Autowired
    private com.zdkj.subway.rca.service.SwCkBomSmallPaymentAlipayService swCkBomSmallPaymentAlipayService;
    @Autowired
    private SwCkBomSmallPaymentService swCkBomSmallPaymentService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
    	List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(4).doReadSync();//真正数据从第五行开始读取     yufang add on 0114
        List<Map<Integer, String>> listAllTicketMap = EasyExcel.read(excelFile).sheet().headRowNumber(2).doReadSync();  //为了读取标题行yufang add on 0114
    	//List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(0).doReadSync();  原来动态写法
        List<Map<String,String>> lineMap = swCkBomSmallPaymentService.selectLineMap();
        List<Map<String,String>> stationMap = swCkBomSmallPaymentService.selectStationMap();
        List<Map<String,String>> ticketTtypeMap = swCkBomSmallPaymentService.selectTicketTtypeMap();

        if (CollectionUtil.isNotEmpty(listMap)) {
            MultipartFileToFile.delteTempFile(excelFile);
            //Map<Integer, String> mapTitle = listMap.get(0); //标题行                   
            //int objSize = (mapTitle.size() - 3) / 2;
            Map<Integer, String> mapAllTitle = listAllTicketMap.get(0); //标题行 yufang add on 0114 begin
            ArrayList<String> arrayTitle = new ArrayList<String>();             
            for(int i = 0; i < mapAllTitle.size(); i++) {         
                String title = mapAllTitle.get(i);              
                if(title!=null){             	   
             	   arrayTitle.add(title);             	   
                }
            }
            //追加固定值，后期再调整为读取Excel里的名称，暂时先写死
            arrayTitle.add(2, "充值"); 
            arrayTitle.add(3, "补票"); 
            arrayTitle.add(4, "罚款"); 
            //yufang add  on 0114   end

            List<SwCkBomSmallPaymentAlipayTmp> listDb = new ArrayList<>();
            //for (int m = 1; m < listMap.size(); m++) {
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                for(int i = 0; i < arrayTitle.size(); i++) {
                    SwCkBomSmallPaymentAlipayTmp tmpObj = new SwCkBomSmallPaymentAlipayTmp();
					String tmpDate = data.get(0);
					if(tmpDate!=null && tmpDate.length()>10){
					  tmpDate = tmpDate.substring(0,10);
					}
                    tmpObj.setTradeDateTmp(tmpDate);//交易日期
                    tmpObj.setLineCodeTmp(data.get(1)); //线路
                    tmpObj.setStationCodeTmp(data.get(2)); //车站
                    if(data.get(2)!=null && "合计".equals(data.get(2))){
                        continue;
                    }
                    tmpObj.setTicketType(getTicketTypeCode(ticketTtypeMap,arrayTitle.get(i)));//票种类型
                    tmpObj.setTicketName(arrayTitle.get(i));//票种名称
                    tmpObj.setAmountTmp(data.get(3 + i * 2));
                    tmpObj.setMoneyTmp(data.get(4 + i * 2));

                    if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())
                            || StringUtils.isEmpty(tmpObj.getAmountTmp())
                            || StringUtils.isEmpty(tmpObj.getMoneyTmp())
                            ) {
                        continue;
                    }
                    if (!parseDate(tmpObj.getTradeDateTmp())) {
                        continue;
                    }
                    final SwCkBomSmallPaymentAlipayTmp obj = ObjectUtils.getDefaultObj(SwCkBomSmallPaymentAlipayTmp.class);
                    BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                    checkErr(obj,lineMap,stationMap);
                    listDb.add(obj);
                }
            }

            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            //this.baseMapper.deleteCretorId(listDb.get(0).getCreatorId());
            return this.saveBatch(listDb);

        }

        return false;
    }

    private String getLineCode (List<Map<String,String>> lineMap,String lineName) {
        for (Map<String,String> map : lineMap){
            if(lineName.equals(map.get("NAME"))){
                return map.get("CODE");
            }
        }
        return "";
    }

    private String getStationCode (List<Map<String,String>> stationMap,String stationName,String lineCode) {
        for (Map<String,String> map : stationMap){
            if(stationName.equals(map.get("NAME")) && lineCode.equals(map.get("LINE_CODE"))){
                return map.get("CODE");
            }
        }
        return "";
    }
    private String getTicketTypeCode (List<Map<String,String>> ticketTtypeMap,String ticketTypeName) {
        for (Map<String,String> map : ticketTtypeMap){
            if(ticketTypeName.equals(map.get("label"))){
                return map.get("value");
            }
        }
        return "";
    }

    private void checkErr(SwCkBomSmallPaymentAlipayTmp obj, List<Map<String,String>> lineMap, List<Map<String,String>> stationMap) {
        //更新字段
        String tradeDateTmp = obj.getTradeDateTmp();
        try {
            Date tradeDate = DateUtils.parseDate(tradeDateTmp, parsePattern);
            obj.setTradeDate(tradeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        } catch (Exception e) {
            obj.setErrMsg("交易日期 为空或格式错误");
        }

        if(StringUtils.isNotEmpty(obj.getLineCodeTmp())){
            String lineCode = getLineCode(lineMap,obj.getLineCodeTmp());
            if(StringUtils.isNotEmpty(lineCode)){
                obj.setLineCode(lineCode);
            } else {
                obj.setErrMsg("线路名称 为空或不规范");
            }

        } else {
            obj.setErrMsg("线路名称 为空");
        }

        if(StringUtils.isNotEmpty(obj.getStationCodeTmp()) && StringUtils.isNotEmpty(obj.getLineCode())){
            String stationCode = getStationCode(stationMap,obj.getStationCodeTmp(),obj.getLineCode());
            if(StringUtils.isNotEmpty(stationCode)){
                obj.setStationCode(stationCode);
            } else {
                obj.setErrMsg("车站名称 为空或不规范");
            }
        } else {
            obj.setErrMsg("车站名称 为空");
        }
        try {
            String amountTmp = obj.getAmountTmp();
            //Integer amount = Integer.parseInt(amountTmp);
            Integer amount = Double.valueOf(amountTmp).intValue();
            obj.setAmount(amount);

        } catch (Exception e) {
            obj.setErrMsg("数量 为空或格式错误");
        }

        try {
            BigDecimal num = new BigDecimal("100");

            String moneyTmp = obj.getMoneyTmp();
            BigDecimal money = new BigDecimal(moneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            money = money.multiply(num);
            obj.setMoney(money.longValue());

        } catch (Exception e) {
            obj.setErrMsg("金额 为空或格式错误");
        }


        //判断数据是否存在  update by yufang on 2021-02-05
//        SwCkBomSmallPaymentAlipay swCkBomSmallPaymentAlipay = new SwCkBomSmallPaymentAlipay();
//		 //BeanUtils.copyProperties(obj, swCkBomSmallPaymentAlipay, "deptId","creatorId","creatorName","createTime");
//        //List<SwCkBomSmallPaymentAlipay> list = swCkBomSmallPaymentAlipayService.list(Wrappers.query(swCkBomSmallPaymentAlipay));
//		swCkBomSmallPaymentAlipay.setLineCode(obj.getLineCode());
//        swCkBomSmallPaymentAlipay.setStationCode(obj.getStationCode());
//        swCkBomSmallPaymentAlipay.setTradeDate(obj.getTradeDate());
//        swCkBomSmallPaymentAlipay.setDelFlag("0");
//
//		int count= swCkBomSmallPaymentAlipayService.count(Wrappers.query(swCkBomSmallPaymentAlipay));
//        if (count > 0 && StringUtils.isEmpty(obj.getErrMsg())) {
//            obj.setErrMsg("数据已存在");
//        }
        
    }

    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(Integer creatorId) {
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(creatorId);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(creatorId);
        //this.baseMapper.saveBatchWithExcelOk(creatorId);
        saveBatchWithExcelCancel(creatorId);
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }
}
